<template>
  <div style="width: 100%;height: 100%;position: relative;padding: 50px;box-sizing: border-box">
    <el-card style="width: 100%;height: 100%;padding: 20px;box-sizing: border-box;">
      <h3>添加电影信息</h3>
      <el-form label-width="100px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="14">
            <el-row :gutter="10" style="margin-top: 20px">
              <el-col :span="12">
                <el-form-item label="电影名称">
                  <el-input placeholder="请输入电影名称" v-model="saveFilmParam.filmName"
                            style="width: 80%;"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电影英文名称">
                  <el-input placeholder="请输入电影英文名称" v-model="saveFilmParam.englishName"
                            style="width: 80%;"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" style="margin-top: 20px">
              <el-col :span="12">
                <el-form-item label="电影上映地区">
                  <el-select placeholder="请选择电影上映地区"
                             clearable
                             filterable
                             remote
                             v-model="saveFilmParam.region"
                             style="width: 80%;">
                    <el-option
                        v-for="item in regionList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上映时间">
                  <el-date-picker
                      type="date"
                      placeholder="选择日期"
                      v-model="saveFilmParam.releaseDate"
                      style="width: 80%;"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" style="margin-top: 20px">
              <el-col :span="12">
                <el-form-item label="电影时长">
                  <el-input placeholder="请输入电影时长"
                            v-model="saveFilmParam.duration"
                            style="width: 80%;"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电影导演">
                  <el-select placeholder="请选择电影导演"
                             clearable
                             filterable
                             remote
                             v-model="saveFilmParam.directorId"
                             style="width: 80%;">
                    <el-option
                        v-for="item in directorData"
                        :label="item.name"
                        :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" style="margin-top: 20px">
              <el-col :span="24">
                <el-form-item label="电影简介">
                  <el-input
                      v-model="saveFilmParam.synopsis"
                      :autosize="{ minRows: 6, maxRows: 4 }"
                      maxlength="200"
                      show-word-limit
                      type="textarea"
                      placeholder="请输入相关信息"
                      style="width: 91%;"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" style="margin-top: 20px">
              <el-col :span="12">
                <el-form-item label="电影状态">
                  <el-input placeholder="请选择电影状态" value="上架"
                            disabled
                            style="width: 80%;">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上映状态">
                  <el-select placeholder="请选择电影上映状态"
                             v-model="saveFilmParam.releaseStatus"
                             @change="releaseStatusChange"
                             style="width: 80%;">
                    <el-option label="上映" value="1"/>
                    <el-option label="预告" value="0"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" style="margin-top: 20px">
              <el-col :span="16">
                <el-form-item label="电影标签">
                  <el-select
                      v-model="saveTagParam.tag"
                      multiple
                      filterable
                      clearable
                      allow-create
                      default-first-option
                      @change="tagChange"
                      placeholder="请选择电影标签"
                  >
                    <el-option
                        v-for="item in tagList"
                        style="width: 80%;"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

          </el-col>
          <el-col :span="10" style="margin-top: 20px;">
            <el-form-item label="电影海报">
              <el-upload
                  v-model:file-list="posterFileList"
                  v-model:action="actionUrl"
                  name="file"
                  limit="1"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
              >
                <el-icon>
                  <Picture/>
                </el-icon>
              </el-upload>
              <el-dialog style="width: 460px; padding: 30px"
                         v-model="posterVisible">
                <img :src="poster"
                     style="width: 400px;"
                     :alt="poster"/>
              </el-dialog>
            </el-form-item>
            <el-form-item label="电影视频"
                          v-show="saveFilmParam.releaseStatus === '1'"
                          style="margin-top: 40px">
              <el-upload
                  v-model:file-list="filmFileList"
                  class="upload-demo"
                  v-model:action="saveFilmUrl"
                  multiple
                  :on-remove="removeFilm"
                  :on-change="handleVideoChange"
                  :on-preview="handleVideoPreview"
                  :limit="1"
              >
                <el-button style="width: 150px;"
                           type="primary">上传视频
                </el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    上传视频文件，支持格式：mp4，文件大小不超过3GB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-dialog style="width: 600px; padding: 30px" v-model="filmVisible">
              <video :src="videoUrl"
                     style="width: 540px;"
                     controls/>
            </el-dialog>
          </el-col>
        </el-row>
      </el-form>
      <el-button type="primary"
                 @click="saveFilm"
                 style="position: absolute;
                   top: 90%;right: 85px;">
        下一步
      </el-button>
      <el-button
          style="position: absolute;top: 90%;right: 15px;"
          @click="cancel"
          type="danger">
        取消
      </el-button>
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, ref, watch} from "vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";
import router from "@/router";

const regionList = ref([]);
const tagList = ref([]);
onMounted(() => {
  loadDictOptions(tagList, 'tag');
  loadDictOptions(regionList, 'nationality');
});

const directorData = ref([]);
const searchDirector = () => {
  axios.get(BASE_URL + '/v1/director/select?')
      .then((response) => {
        if (response.data.code === 2000) {
          directorData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
onMounted(() => {
  searchDirector();
})

/**图片上传相关代码开始**/
const posterFileList = ref([]);
const poster = ref('');
const posterVisible = ref(false);
const actionUrl = ref(BASE_URL + '/v1/filmPoster/upload');
const handleRemove = (uploadFile, uploadFiles) => {
  let posterUrl = uploadFile.response.data;
  axios.post(BASE_URL + '/v1/filmPoster/remove?posterUrl=' + posterUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
const handlePictureCardPreview = (uploadFile) => {
  poster.value = uploadFile.url
  posterVisible.value = true;
}
/**图片上传相关代码结束**/

/**视频上传相关代码开始**/
const filmFileList = ref([]);
const isShow = ref(false);
const saveFilmUrl = ref(BASE_URL + '/v1/filmUrl/upload');
const removeFilm = (uploadFile, uploadFiles) => {
  let filmUrl = uploadFile.response.data;
  axios.post(BASE_URL + '/v1/filmUrl/remove?filmUrl=' + filmUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
          isShow.value = false;
        }
      })
}
const videoUrl = ref('');
const handleVideoChange = (uploadFile) => {
  const file = uploadFile.raw;
  if (!file) return;
  videoUrl.value = URL.createObjectURL(file);
}
const filmVisible = ref(false);
const handleVideoPreview = (uploadFile) => {
  filmVisible.value = true;
}

/**视频上传相关代码结束**/

const releaseStatusChange = (val) => {
  switch (val) {
    case 1:
      isShow.value = true;
      break;
    default:
      isShow.value = false;
      break;
  }
}

const saveFilmParam = ref({
  filmName: '',
  englishName: '',
  region: '',
  releaseDate: '',
  releaseStatus: '',
  duration: '',
  directorId: '',
  synopsis: '',
  poster: '',
  filmUrl: '',
})


/**标签*/
const saveTagParam = ref({
  tag: [],
})

const tagChange = (val) => {
  if (val.length > 4) {
    // 自动移除超出的选项
    saveTagParam.value.tag = val.slice(0, 4);
    ElMessage.warning('最多只能选择四个标签');
  }
}
/**标签*/
const id = ref('');

const saveFilm = () => {
  if (saveFilmParam.value.filmName === '' || !saveFilmParam.value.filmName) {
    errorInfo('电影名称不能为空')
    return;
  }
  if (saveFilmParam.value.englishName === '' || !saveFilmParam.value.englishName) {
    errorInfo('电影英文名称不能为空')
    return;
  }
  if (saveFilmParam.value.region === '' || !saveFilmParam.value.region) {
    errorInfo('电影地区不能为空')
    return;
  }
  if (saveFilmParam.value.releaseDate === '' || !saveFilmParam.value.releaseDate) {
    errorInfo('电影上映时间不能为空')
    return;
  }
  if (saveFilmParam.value.duration === '' || !saveFilmParam.value.duration) {
    errorInfo('电影时长不能为空')
    return;
  }
  if (saveFilmParam.value.directorId === '' || !saveFilmParam.value.directorId) {
    errorInfo('导演不能为空')
    return;
  }
  if (saveFilmParam.value.synopsis === '' || !saveFilmParam.value.synopsis) {
    errorInfo('电影简介不能为空')
    return;
  }
  if (saveFilmParam.value.releaseStatus === '' || !saveFilmParam.value.releaseStatus) {
    errorInfo('电影状态不能为空')
    return;
  }
  if (posterFileList.value.length === 0) {
    errorInfo('电影海报不能为空')
    return;
  }
  if (saveFilmParam.value.releaseStatus === '1' && filmFileList.value.length === 0) {
    errorInfo('电影视频不能为空')
    return;
  }

  if (saveFilmParam.value.releaseStatus === '1') {
    saveFilmParam.value.poster = posterFileList.value[0].response.data;
    saveFilmParam.value.filmUrl = filmFileList.value[0].response.data;
    saveFilmParam.value.tag = saveTagParam.value.tag.join(',');
  } else if (saveFilmParam.value.releaseStatus === '0') {
    saveFilmParam.value.poster = posterFileList.value[0].response.data;
    saveFilmParam.value.tag = saveTagParam.value.tag.join(',');
  }
  let data = qs.stringify(saveFilmParam.value);
  axios.post(BASE_URL + '/v1/film/save', data)
      .then((response) => {
        if (response.data.code === 2000) {
          posterFileList.value = [];
          filmFileList.value = [];
          saveFilmParam.value = {};
          saveTagParam.value = {};
          id.value = response.data.data;
          console.log(id)
          router.push('/insert/second?id=' + id.value)
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}

const cancel = () => {
  ElMessageBox.confirm('确认取消吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    saveTagParam.value = {};
    saveFilmParam.value = {};
    posterFileList.value = [];
    filmFileList.value = [];
    Info('已取消保存');
    router.push('/film')
  }).catch(() => {

  });
}
window.addEventListener('beforeunload', function (e) {
  var message = "您确定要离开此页面吗？未保存的数据可能会丢失。";
  e.returnValue = message;
  return message;
});

</script>

<style scoped>
.el-card {
  border: 0;
  box-shadow: none;
  border-radius: 0;
}
</style>
